package com.atguigu.bigdata.spark.core.rdd.operator.transform

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

/**
  * create by undeRdoG on  2021-06-08  14:26
  * 凡心所向，素履以往，生如逆旅，一苇以航。
  */
object Spark24_RDD_Req {

  def main(args: Array[String]): Unit = {

    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("Operator")
    val sc = new SparkContext(sparkConf)

    val rdd: RDD[String] = sc.textFile("datas/agent.log")

    val mapRDD = rdd.map(line => {
      val fields: Array[String] = line.split(" ")
      ((fields(1),fields(4)),1)
    })

    val reduceRDD= mapRDD.reduceByKey(_ + _)

    val newMapRDD: RDD[(String, (String, Int))] = reduceRDD.map {
      case ((prv, ad), sum) => {
        (prv, (ad, sum))
      }
    }

    val groupRdd: RDD[(String, Iterable[(String, Int)])] = newMapRDD.groupByKey()

    val res: RDD[(String, List[(String, Int)])] = groupRdd.mapValues(
      iter => {
        iter.toList.sortBy(_._2)(Ordering.Int.reverse).take(3)
      }
    )
    res.collect().foreach(println)
  }
}